/**
 * 
 */
package earserpdf;

import java.io.FileOutputStream;
import java.util.Iterator;

import com.lowagie.text.DocumentException;
import com.lowagie.text.Image;
import com.lowagie.text.pdf.PRIndirectReference;
import com.lowagie.text.pdf.PdfDictionary;
import com.lowagie.text.pdf.PdfException;
import com.lowagie.text.pdf.PdfName;
import com.lowagie.text.pdf.PdfObject;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;
import com.lowagie.text.pdf.PdfWriter;

/**
 * <p>Title:RemoveImagePdf</p>
 * <p>Description:replace images in a PDF
 *  It will replace the first image in the first page.
 * </p>
 * @author	xiongf
 * @date	2015年12月8日 下午9:12:45
 * @version 1.0
 */
public class ReplaceImagePdf {
	public static void main(String[] args) throws Exception {
		PdfReader pdf = new PdfReader("E:/Workspace/ItextPDFDemo/pdffolder/207_DEPD1DI0_20160229.pdf");
		PdfStamper stp = new PdfStamper(pdf, new FileOutputStream("E:/Workspace/ItextPDFDemo/pdffolder/207_DEPD1DI0_replace_image.pdf"));
		PdfWriter writer = stp.getWriter();
		Image img = Image.getInstance("image1.png");
		PdfDictionary pg = pdf.getPageN(1);
		PdfDictionary res = (PdfDictionary) PdfReader.getPdfObject(pg.get(PdfName.RESOURCES));
		PdfDictionary xobj = (PdfDictionary) PdfReader.getPdfObject(res.get(PdfName.XOBJECT));
		if (xobj != null) {
			for (Iterator it = xobj.getKeys().iterator(); it.hasNext();) {
				PdfObject obj = xobj.get((PdfName) it.next());
				if (obj.isIndirect()) {
					PdfDictionary tg = (PdfDictionary) PdfReader.getPdfObject(obj);
					PdfName type = (PdfName) PdfReader.getPdfObject(tg.get(PdfName.SUBTYPE));
					if (PdfName.IMAGE.equals(type)) {
						PdfReader.killIndirect(obj);
						Image maskImage = img.getImageMask();
						if (maskImage != null)
							writer.addDirectImageSimple(maskImage);
						writer.addDirectImageSimple(img, (PRIndirectReference) obj);
						break;
					}
				}
			}
		}
		stp.close();
	}

}
